﻿namespace Shell.KnowledgeBase
{
    public class Variable : Term
    {
        public Variable()
        {
            _name = "X" + _identityCounter++;
        }

        public Variable(string name)
        {
            _name = name;
        }

        public override string ToString()
        {
            return "%" + _name;
        }

        public bool Unify(Term b, BindingContext bindingContext)
        {
            var a = this;

            var ai = bindingContext.ResolveTerm(a);
            var fi = bindingContext.ResolveTerm(b);

            if (bindingContext.IsFreeVariable(ai) && bindingContext.IsFreeVariable(fi))
            {
                bindingContext.Bind((Variable)ai, fi);
            }
            else if (bindingContext.IsFreeVariable(ai) && !bindingContext.IsFreeVariable(fi))
            {
                bindingContext.Bind((Variable)ai, fi);
            }
            else if (!bindingContext.IsFreeVariable(ai) && bindingContext.IsFreeVariable(fi))
            {
                bindingContext.Bind((Variable)fi, ai);
            }
            else if (!ai.Equals(fi))
            {
                return false;
            }
            return true;
        }

        private readonly string _name;
        private static int _identityCounter;
    }
}